package com.example.restatr.Atcivity.DigitalLibrary;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LibraryInfoAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private ImageView head;
    private TextView name;
    private TextView workStartAt;
    private TextView serviceTimes;
    private TextView legalExpertiseName;
    private TextView address;
    private ImageView mapImg;
    private RecyclerView rv;
    private DigitalLibraryBean.RowsBean data;
    private List<LibraryCommentBean.DataBean> dataBeans = new ArrayList<>();
    private adapter adapter = new adapter();
    private TextView bottomText;
    private RelativeLayout pl;
    private EditText plEdText;
    private MaterialButton button;
    private LinearLayout loading;
    private LinearLayout Null;
    private TextView nullText;

    private int pageNum = 1;
    private int total;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_libray_info_at);
        bindView();
        nullText.setText("暂无评价...");
        pl.setVisibility(View.VISIBLE);
        plEdText.setHint("本次看书体验如何，快写下你的评价吧！");
        data = new Gson().fromJson(getIntent().getStringExtra("data"), new TypeToken<DigitalLibraryBean.RowsBean>() {
        }.getType());
        total = getIntent().getIntExtra("total", 0);
        Log.d("TAG", "total: " + total);
        Tools.SetBarTitle(toolbar, barTitle, "图书馆详情", search, this, false);
        Glide.with(this)
                .load(Tools.ip + data.getImgUrl())
                .transform(new RoundedCorners(15))
                .into(head);
        name.setText(data.getName());
        workStartAt.setText(data.getBusinessHours());
        legalExpertiseName.setText(getIntent().getStringExtra("state"));
        serviceTimes.setText(data.getAddress());
        address.setText(data.getDescription());
        Glide.with(this)
                .load(Tools.ip + data.getMapUrl().replaceFirst("/dev-api/", "/prod-api/"))
                .transform(new RoundedCorners(15))
                .into(mapImg);
        GetComment();
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!recyclerView.canScrollVertically(1) && newState == 0) {
                    if (dataBeans.size() < total) {
                        pageNum++;
                        GetComment();
                    } else {
                        bottomText.setText("——到底了——");
                    }
                }
            }
        });

        plEdText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (plEdText.getText().toString().length() > 0) {
                    button.setVisibility(View.VISIBLE);
                } else {
                    button.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PutComment();
            }
        });

    }

    private void bindView() {
        toolbar = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        head = findViewById(R.id.head);
        name = findViewById(R.id.name);
        workStartAt = findViewById(R.id.workStartAt);
        serviceTimes = findViewById(R.id.serviceTimes);
        legalExpertiseName = findViewById(R.id.legalExpertiseName);
        address = findViewById(R.id.address);
        mapImg = findViewById(R.id.mapImg);
        rv = findViewById(R.id.rv);
        bottomText = findViewById(R.id.bottomText);
        pl = findViewById(R.id.pl);
        plEdText = findViewById(R.id.pl_edText);
        button = findViewById(R.id.button);
        loading = findViewById(R.id.loading);
        Null = findViewById(R.id.Null);
        nullText = findViewById(R.id.null_text);
    }

    //发表评论
    private void PutComment() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("libraryId", data.getId());
                jsonObject.put("content", plEdText.getText().toString());
                String token = Tools.Post("/prod-api/api/digital-library/library-comment", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(token);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        plEdText.setText("");
                        pageNum = 1;
                        dataBeans.clear();
                        GetComment();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //评论点赞/取消赞
    private void PostCommentLike(int id, boolean state, int position) {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("commentId", id);
                jsonObject.put("like", state);
                String token = Tools.Post("/prod-api/api/digital-library/library-comment/like", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(token);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        dataBeans.get(position).setMyLikeState(state);
                        if (state) {
                            dataBeans.get(position).setLikeCount(dataBeans.get(position).getLikeCount() + 1);
                        } else {
                            dataBeans.get(position).setLikeCount(dataBeans.get(position).getLikeCount() - 1);
                        }
                        adapter.notifyItemChanged(position);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }).start();
    }

    //获取评论
    private void GetComment() {
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/digital-library/library-comment/list?libraryId=" + data.getId() + "&pageSize=10&pageNum=" + pageNum, MainActivity.sp.getString("token", ""));
            LibraryCommentBean libraryCommentBean = new Gson().fromJson(token, LibraryCommentBean.class);
            dataBeans.addAll(libraryCommentBean.getData());
            runOnUiThread(() -> {
                loading.setVisibility(View.GONE);
                if (dataBeans.size() > 0) {
                    rv.setAdapter(adapter);
                } else {
                    Null.setVisibility(View.VISIBLE);
                }
            });

        }).start();
    }

    class adapter extends Adapter<adapter.viewHolder> {
        class viewHolder extends ViewHolder {
            private ImageView head;
            private LinearLayout likeLL;
            private ImageView likeImg;
            private TextView likeNum;
            private TextView name;
            private TextView date;
            private RatingBar score;
            private TextView level;
            private TextView content;
            private CardView reply;
            private TextView replyTime;
            private TextView replyContent;

            public viewHolder(@NonNull View itemView) {
                super(itemView);
                head = itemView.findViewById(R.id.head);
                likeLL = itemView.findViewById(R.id.likeLL);
                likeImg = itemView.findViewById(R.id.likeImg);
                likeNum = itemView.findViewById(R.id.likeNum);
                name = itemView.findViewById(R.id.name);
                date = itemView.findViewById(R.id.date);
                score = itemView.findViewById(R.id.score);
                level = itemView.findViewById(R.id.level);
                content = itemView.findViewById(R.id.content);
                reply = itemView.findViewById(R.id.reply);
                replyTime = itemView.findViewById(R.id.replyTime);
                replyContent = itemView.findViewById(R.id.replyContent);
            }
        }

        @NonNull
        @Override
        public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate(R.layout.pj_list_item, parent, false);
            return new viewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull viewHolder holder, int position) {
            holder.reply.setVisibility(View.GONE);
            holder.head.setVisibility(View.GONE);
            holder.score.setVisibility(View.GONE);
            holder.level.setVisibility(View.GONE);
            holder.likeLL.setVisibility(View.VISIBLE);
            holder.name.setText(dataBeans.get(position).getUserName());
            holder.date.setText(dataBeans.get(position).getCreateTime().substring(0, 10));
            holder.content.setText(dataBeans.get(position).getContent());
            holder.likeNum.setText(String.valueOf(dataBeans.get(position).getLikeCount()));
            if (dataBeans.get(position).isMyLikeState()) {
                holder.likeImg.setImageResource(R.drawable.ic_baseline_favorite_24);
            } else {
                holder.likeImg.setImageResource(R.drawable.ic_baseline_favorite_border_24);
            }
            holder.likeImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PostCommentLike(dataBeans.get(position).getId(), !dataBeans.get(position).isMyLikeState(), position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return dataBeans.size();
        }

    }


}